//
//  XianhuoDetailVC.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/6/8.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit
import Kingfisher

class XianhuoDetailVC2: UIViewController , UIWebViewDelegate {

    let contentView = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT))
    
    let banner = SliderGalleryPresenter()
    var bannerModels : [String] = []

    var model : XianhuoModel?
    var showStatus = false
    var shareView : UIView?
    var maskView : UIView?

    let SHARE_URL = "http://www.yunshutech.com/order.action#offer?id="
    
    static let VCID = "WebViewController"
    
    var shareObj : ShareObject?
    
    var url : String?
    
    let webView = UIWebView.init()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "现货详情"
        self.view.backgroundColor = UIColor.white
        webView.frame = CGRect.init(x:0,y:0,width:Const.SCREEN_WIDTH,height:Const.SCREEN_HEIGHT)
        webView.backgroundColor = self.view.backgroundColor
        self.view.addSubview(webView)
        //        webView.scrollView.contentInset = UIEdgeInsets(64, 0, 0, 0)
        
        webView.dataDetectorTypes = UIDataDetectorTypes.all
        webView.delegate = self
        webView.scalesPageToFit = true
        
        let buttonView = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named:"dotdotdot.png"), for: .normal)
        button.frame = CGRect(x: 8, y: 4, width: 36, height: 36)
        button.addTarget(self, action: #selector(XianhuoDetailVC.shareAction), for: .touchUpInside)
        buttonView.addSubview(button)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: buttonView)
        self.loadURL(self.url!)
        
        self.shareObj = ShareObject.init()
        self.shareObj?.image = nil
        self.shareObj?.imageUrl = model?.kucunpic
        self.shareObj?.url = SHARE_URL + (model?.xianhuoId)!
        
        self.shareObj?.title = "今日\(model?.company ?? "")\(model?.channelname ?? "")现货"
        self.shareObj?.des = model?.advert

    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.webView.reload()
    }
    
    // MARK: - ***Public Method***
    func loadURL(_ urlString: String) -> Void {
        var url = URL(string: urlString)
        if url == nil {
            url = URL(string:urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
        }
        
        webView.loadRequest(URLRequest(url: url!))
    }
    
    func loadFile(_ path: String) -> Void {
        
        let url = URL(fileURLWithPath: path)
        webView.loadRequest(URLRequest.init(url: url))
        //        let htmlData = try? Data(contentsOf: url)
        //        webView.loadHTMLString(htmlStr, baseURL: nil)
        //        webView.load(htmlData!, mimeType: "text/html", textEncodingName: "utf-8", baseURL: URL() )
    }
    
    func loadHTMLText(_ content: String) -> Void {
        //        let htmlData = NSData(base64EncodedString: content, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
        
        webView.loadHTMLString(content, baseURL: nil)
        //        webView.loadData(htmlData!, MIMEType: "text/html", textEncodingName: "utf-8", baseURL: NSURL() )
    }
    
    func share2WX(_ scene: WXScene) {
        
        if !WXApi.isWXAppInstalled() {
            self.navigationController!.view.makeToast("请安装微信客户端")
            //            return;
        }
        if let img = self.shareObj?.image {
            self.doShare2WX(img, scene:scene)
            return;
        }
        
        guard let url = URL(string:(shareObj?.imageUrl)!) else{
            let image = UIImage.init(named:"logo")
            self.doShare2WX(image!, scene:scene)
            return
        }
        
        KingfisherManager.shared.retrieveImage(with: ImageResource.init(downloadURL:url), options: .none, progressBlock: nil) { (image, error, cacheType, url) in
            if error == nil {
                self.doShare2WX(image!, scene:scene)
                
            }else { //图片下载失败，默认图片
                //生成缩略图
                let image = UIImage.init(named:"logo")
                self.doShare2WX(image!, scene:scene)
            }
        }
        
        
    }
    
    func doShare2WX(_ image:UIImage ,scene: WXScene) {
        let ext = WXWebpageObject()
        ext.webpageUrl = self.shareObj?.url
        
        let message = WXMediaMessage()
        if scene == WXSceneTimeline {
            message.title = shareObj?.des
            message.description = nil
        }else{
            message.title = shareObj?.title
            message.description = shareObj?.des
        }
        message.mediaObject = ext
        message.mediaTagName = "MyPic"
        
        let req=SendMessageToWXReq()
        req.text=nil
        req.bText=false
        req.scene=Int32(scene.rawValue)
        
        let size = CGSize.init(width: 120, height: 120)
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        image.draw( in: CGRect.init(origin: CGPoint.zero, size: size ) )
        let thumbImage=UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        message.thumbData=thumbImage!.jpegData(compressionQuality: 0.6)
        req.message=message
        WXApi.send(req)
    }
    
    func onTapWeibo() {
        if (!WeiboSDK.isWeiboAppInstalled()) {
            self.navigationController!.view.makeToast("请安装新浪微博客户端")
            return;
        }
        if let img = self.shareObj?.image {
            self.share2Weibo(img)
            return
        }
        
        guard  let url = URL(string:(shareObj?.imageUrl)!) else {
            let image = UIImage.init(named:"logo")
            self.share2Weibo(image!)
            return
        }
        
        KingfisherManager.shared.retrieveImage(with: ImageResource.init(downloadURL:url), options: .none, progressBlock: nil) { (image, error, cacheType, url) in
            if error == nil {
                self.share2Weibo(image!)
                
            }else { //图片下载失败，默认图片
                //生成缩略图
                let image = UIImage.init(named:"logo")
                self.share2Weibo(image!)
            }
        }
    }
    
    func share2Weibo(_ image:UIImage) {
        
        let webpageObject = WBWebpageObject()
        webpageObject.webpageUrl = self.shareObj?.url
        webpageObject.objectID = ""
        webpageObject.title = "今日\(model?.company ?? "")" + (self.shareObj?.des)!
        
        let message = WBMessageObject()
        message.mediaObject = webpageObject
        //            if text != nil {
        //                message.text = text!
        //            }
        
        let sendMessageToWeiboRequest = WBSendMessageToWeiboRequest()
        sendMessageToWeiboRequest.message = message
        
        let size = CGSize.init(width: 100, height: 100)
        
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        image.draw( in: CGRect.init(origin: CGPoint.zero, size: size) )
        let thumbImage=UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        webpageObject.thumbnailData = thumbImage!.jpegData(compressionQuality: 0.6)
        WeiboSDK.send(sendMessageToWeiboRequest)
    }
    
    func onTapQQ() {
        
        if !QQApiInterface.isQQInstalled() {
            self.navigationController!.view.makeToast("请安装手机QQ客户端")
            return;
        }
        
        let newsUrl = URL(string: (self.shareObj?.url)!)
        let title = self.shareObj?.title
        let description = self.shareObj?.des
        var previewImageUrl = URL(string: "http://www.yunshutech.com/pictureService/showImage.action?type=0&filename=ccbe074f-b85f-454b-bc25-b1f977046222.png")
        if let url = URL(string: (self.shareObj?.imageUrl)!) {
            previewImageUrl = url
        }
        let newsObj = QQApiNewsObject(url: newsUrl, title: title, description: description,
                                      previewImageURL: previewImageUrl,
                                      targetContentType: QQApiURLTargetTypeNews)
        let req = SendMessageToQQReq(content: newsObj)
        QQApiInterface.send(req)
    }
    
    
    func onTapQzone() {
        
        
        let newsUrl = URL(string: (self.shareObj?.url)!)
        let title = self.shareObj?.title
        let description = self.shareObj?.des
        let previewImageUrl = URL(string: (self.shareObj?.imageUrl)!)
        let newsObj = QQApiNewsObject(url: newsUrl, title: title, description: description,
                                      previewImageURL: previewImageUrl,
                                      targetContentType: QQApiURLTargetTypeNews)
        let req = SendMessageToQQReq(content: newsObj)
        QQApiInterface.sendReq(toQZone: req)
        
    }
    
    @IBAction func onTapLove(_ sender: Any) {
    }
    
    public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool
    {
        //        let url = request.url;
        //        if url?.scheme == "tel" {
        //            UIApplication.shared.openURL(url!)
        //        }
        return true;
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        webView.stringByEvaluatingJavaScript(from: "var element = document.createElement('meta');  element.name = \"viewport\";  element.content = \"width=device-width,initial-scale=1.0,minimum-scale=0.5,maximum-scale=3,user-scalable=1\"; var head = document.getElementsByTagName('head')[0]; head.appendChild(element);")
    }

    func shareAction() {
        if self.shareView == nil {
            var height: Int = 196
            if self.model?.userid == User.get.userId {
                height += 49
            }
            self.shareView = UIView.init(frame: CGRect.init(x: 0, y: Int(Const.SCREEN_HEIGHT) - height, width: Int(Const.SCREEN_WIDTH), height: height))
            self.shareView?.backgroundColor = Const.WTM_WHITE_SMOKE
            let spacing = (Const.SCREEN_WIDTH - 50*5) / 6
            
            let timelineImg = UIImageView.init(frame: CGRect.init(x: spacing, y: 40, width: 50, height: 50))
            timelineImg.image = UIImage.init(named: "timeline2.png")
            timelineImg.tag = 1
            timelineImg.isUserInteractionEnabled = true
            self.shareView?.addSubview(timelineImg)
            
            let timeLabel = UILabel.init(frame: CGRect.init(x: spacing, y: 103, width: 50, height: 14))
            timeLabel.text = "朋友圈"
            timeLabel.font = UIFont.systemFont(ofSize: 13)
            timeLabel.textColor = Const.WTM_GRAY_FONT
            timeLabel.textAlignment = .center
            self.shareView?.addSubview(timeLabel)
            
            let sessionImg = UIImageView.init(frame: CGRect.init(x: spacing + (spacing + 50), y: 40, width: 50, height: 50))
            sessionImg.image = UIImage.init(named: "session2.png")
            sessionImg.isUserInteractionEnabled = true
            sessionImg.tag = 2
            self.shareView?.addSubview(sessionImg)
            let sessionLabel = UILabel.init(frame: CGRect.init(x: spacing+(spacing + 50), y: 103, width: 50, height: 14))
            sessionLabel.text = "微信"
            sessionLabel.font = UIFont.systemFont(ofSize: 13)
            sessionLabel.textColor = Const.WTM_GRAY_FONT
            sessionLabel.textAlignment = .center
            self.shareView?.addSubview(sessionLabel)
            
            let sinaImg = UIImageView.init(frame: CGRect.init(x: spacing+(spacing + 50)*2, y: 40, width: 50, height: 50))
            sinaImg.image = UIImage.init(named: "weibo2.png")
            sinaImg.tag = 3
            sinaImg.isUserInteractionEnabled = true
            let sinaLabel = UILabel.init(frame: CGRect.init(x: spacing+(spacing + 50)*2, y: 103, width: 50, height: 14))
            sinaLabel.text = "微博"
            sinaLabel.font = UIFont.systemFont(ofSize: 13)
            sinaLabel.textColor = Const.WTM_GRAY_FONT
            sinaLabel.textAlignment = .center
            self.shareView?.addSubview(sinaLabel)
            self.shareView?.addSubview(sinaImg)
            
            let qqImg = UIImageView.init(frame: CGRect.init(x: spacing+(spacing + 50)*3, y: 40, width: 50, height: 50))
            qqImg.image = UIImage.init(named: "QQ2.png")
            qqImg.tag = 4
            qqImg.isUserInteractionEnabled = true
            let qqLabel = UILabel.init(frame: CGRect.init(x: spacing+(spacing + 50)*3, y: 103, width: 50, height: 14))
            qqLabel.text = "QQ"
            qqLabel.font = UIFont.systemFont(ofSize: 13)
            qqLabel.textColor = Const.WTM_GRAY_FONT
            qqLabel.textAlignment = .center
            self.shareView?.addSubview(qqLabel)
            self.shareView?.addSubview(qqImg)
            
            let qzoneImg = UIImageView.init(frame: CGRect.init(x: spacing+(spacing + 50)*4, y: 40, width: 50, height: 50))
            qzoneImg.image = UIImage.init(named: "QZone2.png")
            qzoneImg.tag = 5
            qzoneImg.isUserInteractionEnabled = true
            let qzoneLabel = UILabel.init(frame: CGRect.init(x: spacing+(spacing + 50)*4, y: 103, width: 50, height: 14))
            qzoneLabel.text = "QQ空间"
            qzoneLabel.font = UIFont.systemFont(ofSize: 13)
            qzoneLabel.textColor = Const.WTM_GRAY_FONT
            qzoneLabel.textAlignment = .center
            self.shareView?.addSubview(qzoneLabel)
            self.shareView?.addSubview(qzoneImg)
            
            let tap = UITapGestureRecognizer.init(target: self, action: #selector(XianhuoDetailVC.onTapShare(_:)))
            let tap1 = UITapGestureRecognizer.init(target: self, action: #selector(XianhuoDetailVC.onTapShare(_:)))
            let tap2 = UITapGestureRecognizer.init(target: self, action: #selector(XianhuoDetailVC.onTapShare(_:)))
            let tap3 = UITapGestureRecognizer.init(target: self, action: #selector(XianhuoDetailVC.onTapShare(_:)))
            let tap4 = UITapGestureRecognizer.init(target: self, action: #selector(XianhuoDetailVC.onTapShare(_:)))
            timelineImg.addGestureRecognizer(tap)
            sessionImg.addGestureRecognizer(tap1)
            sinaImg.addGestureRecognizer(tap2)
            qqImg.addGestureRecognizer(tap3)
            qzoneImg.addGestureRecognizer(tap4)

            if self.model?.userid == User.get.userId {
                let btn1 = UIButton.init(frame: CGRect.init(x: 0, y: 147, width: Int(Const.SCREEN_WIDTH), height: 49))
                btn1.backgroundColor = UIColor.white
                btn1.titleLabel?.font = UIFont.systemFont(ofSize: 14)
                btn1.setTitleColor(Const.WTM_BLACK, for: .normal)
                btn1.addTarget(self, action: #selector(XianhuoDetailVC2.addKuncun(_:)), for: .touchUpInside)
                btn1.setTitleColor(UIColor.black, for: .normal)
                btn1.setTitle("添加库存表和报价", for: .normal)
                self.shareView?.addSubview(btn1)
                
                let line = UIView(frame: CGRect(x: 0, y: 196 - Const.ONE_PIXEL, width: Const.SCREEN_WIDTH, height: Const.ONE_PIXEL))
                line.backgroundColor = Const.WTM_WHITE_SMOKE;
                self.shareView?.addSubview(line)
            }
            
            let btn = UIButton.init(frame: CGRect.init(x: 0, y: height - 49, width: Int(Const.SCREEN_WIDTH), height: 49))
            btn.backgroundColor = UIColor.white
            btn.addTarget(self, action: #selector(XianhuoDetailVC2.cancelShare(_:)), for: .touchUpInside)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            btn.setTitleColor(Const.WTM_BLACK, for: .normal)
            btn.setTitle("取消", for: .normal)
            self.shareView?.addSubview(btn)
            
            maskView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT))
            maskView?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.4)
        }
        self.navigationController?.view.addSubview(maskView!)
        maskView?.addSubview(self.shareView!)
    }
    
    @objc func cancelShare(_ sender:UIView){
        maskView?.removeFromSuperview()
    }
    
    @objc func onTapShare(_ sender:UITapGestureRecognizer) {
        let senderView = sender.view
        if senderView?.tag == 1 {
            self.share2WX(WXSceneTimeline)
        }else if senderView?.tag == 2 {
            self.share2WX(WXSceneSession)
        }else if senderView?.tag == 3 {
            self.onTapWeibo()
        }else if senderView?.tag == 4 {
            self.onTapQQ()
        }else if senderView?.tag == 5 {
            self.onTapQzone()
        }
    }
    
    @objc func addKuncun(_ sender:UIView) {
        maskView?.removeFromSuperview()
        let vc = AddKucunVC()
        vc.model = self.model!
        self.navigationController?.pushViewController(vc)
    }
}
